package org.yimon.tool.algo.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author yimon.gao
 * @Description 二叉树的层序遍历
 * @Date 2024/8/20 下午3:45
 */
public class LeetCode_102_LevelOrder {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3, new TreeNode(9, new TreeNode(8), new TreeNode(11)), new TreeNode(20, new TreeNode(15), new TreeNode(7)));
        System.out.println(LeetCode_102_LevelOrder.levelOrder(root));
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        //特殊情况判断
        if (root == null) {
            return result;
        }
        preorder(root, result, 1);
        return result;
    }

    private static void preorder(TreeNode root, List<List<Integer>> result, int level) {
        if (root == null) {//节点为null，说明已经遍历完，结束
            return;
        }
        //判断result结果长度与层级是否匹配，匹配说明该层不是第一次添加元素，否是是第一次添加元素
        if (result.size() < level) {
            //说明该层是第一次添加元素，需要进行初始化
            List<Integer> levelList = new ArrayList<>();
            levelList.add(root.val);
            result.add(levelList);
        } else {
            //说明该层不是第一次添加元素，取出集合加入即可
            result.get(level - 1).add(root.val);
        }
        //往下一层进行递归
        level++;
        preorder(root.left, result, level);//递归左节点
        preorder(root.right, result, level);//递归右节点
    }

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
